<script setup>
import { useRouter } from 'vue-router'
import { reactive, ref } from "vue";
import { removeToken } from "@/composables/cookie";
import { uploadFile } from "@/api/common/file"
import { updatePassword, updateUserInfo } from "@/api/common/user"
import { showMessage, showModel } from "@/composables/util.js";
import { UserFilled } from "@element-plus/icons-vue";
// 控制个人信息弹出框
let info = ref(false)
let password = ref(false)
const router = useRouter()
// 从浏览器本地存储中取出用户信息
let userInfo = JSON.parse(localStorage.getItem("userInfo"))
const form1 = reactive({
  id: userInfo.id,
  username: userInfo.username,
  avatar: userInfo.avatar,
  token: userInfo.token
})
const form2 = reactive({
  username: userInfo.username,
  password: '',
  newPassword: '',
  surePassword: ''
})

// 退出登录方法
const logout = () => {
  showModel('是否退出登录?').then(() => {
    // 删除cookie中的token
    removeToken()
    // 删除Local Storage中的userInfo
    localStorage.removeItem('userInfo')
    showMessage('退出登录成功!')
    // 跳转登录页
    router.push('/login')
  })
}

const handleAvatarChange = (file) => {
  // 创建表单对象
  let formData = new FormData()
  formData.append('file', file.raw)
  // 调用后台文件上传接口
  uploadFile(formData).then((e) => {
    // 响参失败，提示错误消息
    if (e.data.success == false) {
      let message = e.message
      showMessage(message, 'error')
      return
    }
    // 成功则设置头像链接，并提示成功
    form1.avatar = e.data.data
    console.log("头像地址："+form1.avatar)
  })
}

// 修改用户信息
const saveInfo = () => {
  // 调用后端修改用户信息接口
  updateUserInfo(form1).then((res) => {
    if(res.data.success === true){
      // 提示修改成功
      showMessage('修改成功')
      // 更新存储的用户信息JSON格式到Local Storage(浏览器本地存储) 中
      localStorage.setItem("userInfo", JSON.stringify(res.data.data))
      // 更新之前获取的用户信息变量
      userInfo = JSON.parse(localStorage.getItem("userInfo"))
      info = false
      window.location.reload();
    }else {
      let message = res.data.message
      console.log(message)
      // 提示消息
      showMessage(message, 'error')
    }
  })
}

// 修改用户密码
const savePassword = () => {
  if(form2.newPassword != form2.surePassword) {
    showMessage('两次密码输入不一致', 'error')
    return
  }
  // 调用后端修改用户信息接口
  updatePassword(form2).then((res) => {
    if(res.data.success === true){
      // 提示修改成功
      showMessage('修改成功')
      // 删除cookie中的token
      removeToken()
      // 删除Local Storage中的userInfo
      localStorage.removeItem('userInfo')
      // 重新跳转登录页面
      router.push('/login')
    }else {
      let message = res.data.message
      console.log(message)
      // 提示消息
      showMessage(message, 'error')
    }
  })

}

</script>

<template>
  <div class="header-container flex-box">
    <div class="header-left flex-box">
      <img src="../assets/study.png">
      <div class="title">高校互联网技术在线学习平台</div>
    </div>
    <div class="header-right">
      <el-dropdown>
        <div class="el-dropdown-link flex-box">
          <el-avatar :src="userInfo.avatar" :icon="UserFilled" style="background-color: #8ac8ff"/>
          <p class="user-name">{{ userInfo.username }}</p>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="info=true">个人信息</el-dropdown-item>
            <el-dropdown-item @click="password=true">修改密码</el-dropdown-item>
            <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
  <!--要单独拿出来，否则会被循环重复渲染-->
  <!--个人信息对话框-->
  <el-dialog v-model="info" title="个人信息" width="500px"  class="custom-dialog">
    <el-form :model="form1" label-width="80px" style="padding: 10px;">
      <el-form-item label="头像">
        <div style="display: flex; align-items: center;">
          <el-avatar :src="form1.avatar" :icon="UserFilled" style="background-color: #8ac8ff; margin-right: 10px;" />
          <el-upload
              :on-change="handleAvatarChange"
              :auto-upload="false"
              :show-file-list="false"
              :file-list="fileList">
            <el-button size="small" type="primary">修改头像</el-button>
          </el-upload>
        </div>
      </el-form-item>

      <el-form-item label="用户名">
        <el-input v-model="form1.username" autocomplete="off" placeholder="请输入用户名" style="width: 130px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="text-align: right;">
        <el-button @click="info = false">取消</el-button>
        <el-button type="primary" @click="saveInfo">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!--修改密码对话框-->
  <el-dialog v-model="password" title="修改密码" width="500px" class="custom-dialog">
    <el-form :model="form2" label-width="80px" style="padding: 10px;">
      <el-form-item label="旧密码">
        <el-input type="password" v-model="form2.password" autocomplete="off" placeholder="请输入旧密码" style="width: 200px"/>
      </el-form-item>
      <el-form-item label="新密码">
        <el-input type="password" v-model="form2.newPassword" autocomplete="off" placeholder="请输入新密码" style="width: 200px" />
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input type="password" v-model="form2.surePassword" autocomplete="off" placeholder="请确认新密码" style="width: 200px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="text-align: right;">
        <el-button @click="password = false">取消</el-button>
        <el-button type="primary" @click="savePassword">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
@primary: #006eff;
@hover-blue: rgba(255,255,255,0.1);

.flex-box {
  display: flex;
  align-items: center;
  height: 100%;
}

.header-container {
  justify-content: space-between;
  height: 60px;
  background: linear-gradient(145deg, darken(@primary, 5%) 0%, @primary 100%);
  padding: 0 25px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  position: relative;
  z-index: 1000;

  .header-left {
    height: 100%;
    img {
      width: 40px;
      height: 40px;
      margin-left: 8px;
      transition: transform 0.3s ease;
      &:hover {
        transform: rotate(-10deg) scale(1.1);
      }
    }
    .title {
      margin-left: 12px;
      font-size: 20px;
      font-weight: 700;
      color: #fff;
      text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
      letter-spacing: 1px;
    }
  }

  .header-right {
    .el-dropdown-link {
      cursor: pointer;
      padding: 8px 12px;
      border-radius: 30px;
      transition: all 0.3s ease;

      &:hover {
        background: @hover-blue;
        .user-name {
          color: rgba(255,255,255,0.9);
        }
        .el-avatar {
          transform: scale(1.1);
        }
      }

      .el-avatar {
        transition: transform 0.3s ease;
        box-shadow: 0 2px 6px rgba(0,0,0,0.1);
      }

      .user-name {
        margin-left: 10px;
        color: rgba(255,255,255,0.8);
        transition: color 0.3s ease;
        font-weight: 500;
      }
    }
  }
}

/* 深度定制对话框样式 */
:deep(.custom-dialog) {
  border-radius: 12px;
  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    margin-right: 0;
    .el-dialog__title {
      font-size: 18px;
      color: #333;
      font-weight: 600;
    }
  }

  .el-form-item {
    margin-bottom: 22px;
    &__label {
      color: #666;
      font-weight: 500;
    }
  }

  .el-input {
    width: 220px;
    &__inner {
      border-radius: 8px;
    }
  }

  .dialog-footer {
    padding: 0 20px 20px;
    .el-button {
      padding: 10px 20px;
      border-radius: 8px;
      &--primary {
        background: @primary;
        border-color: @primary;
        &:hover {
          opacity: 0.9;
        }
      }
    }
  }
}

/* 下拉菜单优化 */
:deep(.el-dropdown-menu) {
  border-radius: 8px;
  padding: 8px 0;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);

  .el-dropdown-menu__item {
    padding: 10px 16px;
    font-size: 14px;
    transition: all 0.2s ease;

    &:hover {
      background: lighten(@primary, 40%);
      color: @primary;
    }

    &:not(:last-child) {
      margin-bottom: 4px;
    }
  }
}

/* 上传按钮美化 */
:deep(.el-upload) {
  .el-button {
    padding: 8px 16px;
    border-radius: 20px;
    background: @primary;
    border-color: @primary;
    &:hover {
      background: darken(@primary, 5%);
    }
  }
}
</style>
